import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { tap, switchMap, map } from 'rxjs/operators';
import { GroupModelPermissionPK } from 'src/app/domain/group';
import {
  PermissionEnum,
  Model,
  ModelPermission,
  SysroleModelPermissionPK,
} from 'src/app/domain/sparrow';
import { ModelService } from 'src/app/service/model.service';
import { EmployeeSearchComponent } from '../employee-search/employee-search.component';
import { GroupSearchComponent } from '../group-search/group-search.component';
import { LevelSearchComponent } from '../level-search/level-search.component';
import { OrganizationSearchComponent } from '../organization-search/organization-search.component';
import { PermissionSelectComponent } from '../permission-select/permission-select.component';
import { RoleSearchComponent } from '../role-search/role-search.component';
import { SysroleSearchComponent } from '../sysrole-search/sysrole-search.component';

@Component({
  selector: 'app-set-model-permission',
  templateUrl: './set-model-permission.component.html',
  styleUrls: ['./set-model-permission.component.css'],
})
export class SetModelPermissionComponent implements OnInit {
  permissionKeys: any[] = Object.keys(PermissionEnum).map((label) => ({
    label: PermissionEnum[label as keyof typeof PermissionEnum],
    value: label,
  }));

  inputValue?: string;

  onChange(value: string): void {
    console.log(value);
  }
  models: Model[] = [];

  constructor(
    private router: ActivatedRoute,
    private modelService: ModelService
  ) {}

  // listOfOption = ['Apples', 'Nails', 'Bananas', 'Helicopters'];
  listOfSelectedValue: any[] = [];

  isNotSelected(value: string): boolean {
    return this.listOfSelectedValue.indexOf(value) === -1;
  }

  listOfTagOptions?: any[];
  listOfOption?: any[];
  ngOnInit(): void {
    // this.models.push({name:"bbbb", nameTxt:"aaaa"});
    // console.log(this.router.params)
    // this.listOfOption = this.permissionKeys
    // const models$:Observable<Model[]> = this.router.params.pipe(tap(params=>console.log(params)),
    //   switchMap(params=>
    //     this.modelService.getModelsInId(JSON.parse(params['ids'])).pipe(map(res => res = res.content))
    //   )
    // );
    // models$.subscribe(res=>{
    //   this.models = res;
    // });
  }

  onClose(): void {
    console.log('tag was closed.');
  }
  radioValue: string = '';
  allChecked = false;
  indeterminate = true;

  updateAllChecked(): void {
    this.indeterminate = false;
    if (this.allChecked) {
      this.permissionKeys = this.permissionKeys.map((item) => ({
        ...item,
        checked: true,
      }));
    } else {
      this.permissionKeys = this.permissionKeys.map((item) => ({
        ...item,
        checked: false,
      }));
    }
  }

  updateSingleChecked(): void {
    if (this.permissionKeys.every((item) => !item.checked)) {
      this.allChecked = false;
      this.indeterminate = false;
    } else if (this.permissionKeys.every((item) => item.checked)) {
      this.allChecked = true;
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }
  }

  @ViewChild(PermissionSelectComponent)
  permissionSelectComponent!: PermissionSelectComponent;
  addPermission() {
    console.log(
      'permissiontyp',
      this.permissionSelectComponent.radioValue,
      this.permissionSelectComponent.listOfSelectedPermissionValue
    );
    this.modelService
      .addPermission(
        this.permissionOp(this.permissionSelectComponent.radioValue!)
      )
      .subscribe();
  }

  @ViewChild(EmployeeSearchComponent)
  employeeSearchComponent!: EmployeeSearchComponent;
  @ViewChild(SysroleSearchComponent) sysroleSearchComponent!: SysroleSearchComponent;
  @ViewChild(GroupSearchComponent) groupSearchComponent!: GroupSearchComponent;
  @ViewChild(OrganizationSearchComponent)
  organizationSearchComponent!: OrganizationSearchComponent;
  @ViewChild(RoleSearchComponent) roleSearchComponent!: RoleSearchComponent;
  @ViewChild(LevelSearchComponent) levelSearchComponent!: LevelSearchComponent;

  permissionOp(permissionType: string): ModelPermission {
    let permissions: ModelPermission = {employeeModelPermissionPKs:[],sysroleModelPermissionPKs:[]};
    this.models.forEach((model) => {
      this.permissionSelectComponent.listOfSelectedPermissionValue.forEach(
        (p) => {
          this.employeeSearchComponent.treeService.selectListSelection.selected.forEach(f=>{
            permissions.employeeModelPermissionPKs!.push(
              {
                employeeId: f.id!,
                modelName: model.name,
                permission: p,
                permissionType: permissionType
              }
            );
          })

          this.sysroleSearchComponent.selectedUser!.forEach(f=>{
            permissions.sysroleModelPermissionPKs!.push(
              {
                sysroleId: f.id,
                modelName: model.name,
                permission: p,
                permissionType: permissionType
              }
            );
          })

          // this.organizationSearchComponent.selectListSelection.selected.forEach(
          //   (f) => {
          //     permissions.groupModelPermissionPKs!.push({
          //       groupId: f.me.id!,
          //       modelName: model.name,
          //       permission: p,
          //       permissionType: permissionType,
          //     });
          //   }
          // );

          // this.organizationSearchComponent.selectListSelection.selected.forEach(
          //   (f) => {
          //     permissions.organizationModelPermissionPKs!.push({
          //       organizationId: f.me.id!,
          //       modelName: model.name,
          //       permission: p,
          //       permissionType: permissionType,
          //     });
          //   }
          // );

          // this.roleSearchComponent.selectListSelection.selected.forEach((f) => {
          //   permissions.roleModelPermissionPKs!.push({
          //     roleId: f.me.id!,
          //     modelName: model.name,
          //     permission: p,
          //     permissionType: permissionType,
          //   });
          // });

          // this.levelSearchComponent.selectListSelection.selected.forEach(
          //   (f) => {
          //     permissions.levelModelPermissionPKs!.push({
          //       levelId: f.me.id!,
          //       modelName: model.name,
          //       permission: p,
          //       permissionType: permissionType,
          //     });
          //   }
          // );
        }
      );
    });
    return permissions;
  }

  delPermission() {
    this.modelService
      .delPermission(this.permissionOp(this.radioValue))
      .subscribe();
  }

  value: string[] = ['0-0-0'];
  nodes = [
    {
      title: 'Node1',
      value: '0-0',
      key: '0-0',
      children: [
        {
          title: 'Child Node1',
          value: '0-0-0',
          key: '0-0-0',
          isLeaf: true,
        },
      ],
    },
    {
      title: 'Node2',
      value: '0-1',
      key: '0-1',
      children: [
        {
          title: 'Child Node3',
          value: '0-1-0',
          key: '0-1-0',
          isLeaf: true,
        },
        {
          title: 'Child Node4',
          value: '0-1-1',
          key: '0-1-1',
          isLeaf: true,
        },
        {
          title: 'Child Node5',
          value: '0-1-2',
          key: '0-1-2',
          isLeaf: true,
        },
      ],
    },
  ];
}
